<?php
class Payment_Transaction extends Data_Item
{
    public static function instanceByOutTradeNo ($out_trade_no)
    {
        $id = DB::select('id')
            ->from('mod_payment_transaction')
            ->where('out_trade_no', '=', $out_trade_no)
            ->execute()
            ->get('id');

        if ($id > 0)
            return new Payment_Transaction($id);
        else
            return NULL;
    }

    public function __construct ($id = NULL)
    {
        parent::__construct($id);

        $this->_nid = $id;
        $this->_commTableName  = 'mod_payment_transaction';
        $this->_commPrimaryKey = 'id';
    }

    // 添加支付交易
    // @string title 
    // @int money (分)
    public function create ($uid, $shopId,$shopIdGroup,$title, $money)
    {
        $shopIdGroup=trim($shopIdGroup);
        $row = array(
            'status'    => 'UNPAID',
            'total_fee' => $money,
            'body'      => $title,

            'uid'       => $uid,
            'shopId'    => $shopId,
            'shopIdGroup'    => $shopIdGroup,
            'created'   => DB::expr('unix_timestamp(now())'),
            'changed'   => DB::expr('unix_timestamp(now())'),
        );

        $id = $this->insert($row);
        if ($id > 0)
        {
            $out_trade_no = sprintf("%s%s%06d", date("Ymd"), date("Hi"), $id);
            $this->update(array('out_trade_no' => $out_trade_no), array('id', '=', $id));
            return $id;
        }

        return FALSE;
    }

    // 通知支付成功
    public function notify_paid ($platform, 
        $transactionId, $merchantId = NULL, $resultCode = NULL, $returnCode = NULL)
    {
        $detail = $this->detail();
        $iResultCode = Arr::get($detail, 'resultCode');
        $iReturnCode = Arr::get($detail, 'returnCode');

        if ($iResultCode == 'SUCCESS' || $iReturnCode == 'SUCCESS')
            return;

        $row = array(
            'platform'      => $platform,
            'status'        => 'PAID',
            'transactionId' => $transactionId,
            'merchantId'    => $merchantId,
            'resultCode'    => $resultCode,
            'returnCode'    => $returnCode,
            'changed'       => DB::expr('unix_timestamp(now())'),
        );

        $rows = DB::update('mod_payment_transaction')
            ->set($row)
            ->where('id', '=', $this->_nid)
            ->execute();

        if ($rows > 0)
        {
            $order = new Order;
            $order->setOrdersPaidByTransactionId($this->_nid);
        }
    }
}
